from hashlib import md5
from time import time
from urllib import url2pathname

APP_ID = 2242336
APP_SECRET = "Is91pYIxf997UYt8yjy4"
NOT_CORRECT_ID = 'NaN' 


class VkCookieError(Exception):
    pass


def get_vk_user_id(vk_user_cookie):
    """Checks authorization"""
    vk_user_cookie = url2pathname(vk_user_cookie)
    data_array = {}
    vk_data = vk_user_cookie.split('&')
    valid_keys = ('expire', 'mid', 'secret', 'sid', 'sig')    
    try:    
        # parse cookie    
        for vk_data_param in vk_data:
            key, value = vk_data_param.split('=')
            if not key or not value or key not in valid_keys:
                raise VkCookieError
            data_array[key] = value
        for key in valid_keys:
            if not data_array[key]:
                raise VkCookieError
        
        # create string for md5
        strings = []
        for key in sorted(data_array.keys()):
            if key != 'sig':
                strings.append('{0}={1}'.format(key, data_array[key]))
        strings.append(APP_SECRET)
        sig_md5 = md5(''.join(strings)).hexdigest()
        
        if data_array['sig'] != sig_md5 or int(data_array['expire']) <= time():
            raise VkCookieError
    except VkCookieError:
        user_id = NOT_CORRECT_ID
    else:
        user_id = data_array['mid']
    return user_id